import express from "express";
import { PrismaClient, Prisma } from "@prisma/client";
import { CreateId, Check, Result, Time, Utils } from "@/utils";

const prisma = new PrismaClient();
const router = express.Router();

router.get("/search", async (req, res) => {
   const { role_id }: Permission.Search = req.query as any;
   if (!Check.Required([role_id])) return res.send(Result.Error("参数错误"));

   const role = await prisma.mp_role.findUnique({
      select: { permission: true, super_admin: true },
      where: { id: role_id }
   });
   if (!role) return res.send(Result.Error("当前条目不存在"));

   const routers = await prisma.mp_router.findMany({
      select: {
         id: true,
         meta_label: true,
         parent_id: true,
         level: true
      }
   });

   const routerList = routers.map(item => {
      return {
         ...item,
         disabled: role.super_admin
      };
   });

   const tree = Utils.ListToTree(routerList);
   let ids: string[] = [];

   if (role.super_admin) {
      ids = routers.map(item => item.id);
   } else {
      ids = role.permission.split(",");
   }

   res.send(Result.OK({ tree, ids }));
});

/** 分配权限 */
router.post("/assign", async (req, res) => {
   const { role_id, ids }: Permission.Assign = req.body;
   if (!(ids instanceof Array)) return res.send(Result.Error("参数错误"));

   const str = ids.join(",");

   await prisma.mp_role.update({
      where: { id: role_id },
      data: {
         permission: str
      }
   });

   res.send(Result.OK());
});

export const permission = router;
